package org.luxor.commons.core.exception;

import org.luxor.commons.core.utils.StringUtils;
import org.luxor.commons.core.web.IRestStatus;
import org.luxor.commons.core.web.RestStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 异常定义基类
 *
 * @author XinmingYan @date 2019/9/15 18:18 @version 0.0.1
 */
public class BaseException extends RuntimeException {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 错误码
     */
    private Integer code = RestStatus.ERROR.code();

    /**
     * 异常说明
     */
    private String message;

    /**
     * 异常详情
     */
    private String error;

    public BaseException() {
        super();
    }

    public BaseException(String message) {
        super(message);
        this.message = message;
    }

    public BaseException(String message, Throwable e) {
        super(message, e);
        this.message = message;
        setError(e);
    }

    public BaseException(Integer code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    public BaseException(Integer code, String message, String error) {
        super(message);
        this.code = code;
        this.message = message;
        this.error = error;
    }

    public BaseException(Integer code, String message, Throwable e) {
        super(message, e);
        this.code = code;
        this.message = message;
        setError(e);
    }

    public BaseException(IRestStatus restStatus) {
        super(restStatus.message());
        this.code = restStatus.code();
        this.message = restStatus.message();
    }

    public BaseException(IRestStatus restStatus, String error) {
        super(restStatus.message());
        this.code = restStatus.code();
        this.message = restStatus.message();
        this.error = error;
    }

    public BaseException(IRestStatus restStatus, Throwable e) {
        super(restStatus.message(), e);
        this.code = restStatus.code();
        this.message = restStatus.message();
        setError(e);
    }

    public Map<String, Object> asMap(Boolean isShowErrorDetail) {
        Map map = new LinkedHashMap(3);
        map.put("code", this.code);
        map.put("message", this.message);
        if (error != null && isShowErrorDetail) {
            map.put("error", this.error);
        }
        return map;
    }

    private void setError(Throwable e) {
        logger.error("出现异常错误：", e);
        if (this.message == null) {
            this.message = RestStatus.ERROR.message();
        }
        this.error = StringUtils.toString(e);
    }

}
